<!-- eslint-disable vue/multi-word-component-names -->
<template>
  <div class="index" :class="{ 'blur-background': isBlur }">
    <div class="time" @dblclick="handleDoubleClick">
      {{ newDate }}
    </div>
    <div class="search-box">
      <Qselect :data="searchEngines" @optionClick="setSearchEngineKey" />
      <div class="search-input" @click="selectTextCuntion = -1">
        <input ref="inputRef" :class="{ focus: showHistory }" class="search" v-model="queryText" @focus="focus"
          @blur="blur" @keydown.enter="search_engine_query" @input="getQueryHistory(queryText)" />
        <div v-show="showHistory" class="history-list">
          <ul>
            <li @click="setQueryText(item)" v-for="(item, index) in historyList" :key="index"
              :class="{ select: index === selectTextCuntion }">
              <div>{{ item }}</div>
              <button @click.stop="removeHistoryItem(item)">移除</button>
            </li>
          </ul>
        </div>
      </div>
      <button @click="search_engine_query" class="search-button">搜索</button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { type AllowedSearchEnginesOptions } from '@/hooks/index/useSearchEngine.ts';
import { onMounted, ref, watch } from 'vue'
import { formatDate } from '@/utils/time'
import useHistoricalSearch from '@/hooks/index/useHistoricalSearch';
import useSearchEngine from '@/hooks/index/useSearchEngine';
import Qselect from '@/components/Qselect/index.vue';
import { useRouter } from 'vue-router';

const router = useRouter();

const { show: showHistory, add: addHistory, fuzzySearch, remove: removeHistory } = useHistoricalSearch();
const { searchEngines, searchEngineKey, iconSearch, queryText, query } = useSearchEngine();

const isBlur = ref(false)
const isOption = ref(false)
const historyList = ref<string[]>(fuzzySearch(queryText.value));

const search_engine_query = () => {
  query();
  addHistory(queryText.value);
}
const setQueryText = (value: string) => {
  queryText.value = value;
  inputRef.value?.focus();
  search_engine_query()
}

// 监听搜索引擎变化，更新图标
watch(searchEngineKey, async (val) => {
  const svgModule = await import(`@/assets/index/${val}.svg`)
  iconSearch.value = svgModule.default
}, { immediate: true })

// 更新当前时间
const newDate = ref(formatDate('hh:mm:ss'));
setInterval(() => {
  newDate.value = formatDate('hh:mm:ss')
}, 1000)

const inputRef = ref<HTMLInputElement | null>(null)

// 获取查询历史记录
const getQueryHistory = (val: string) => {
  selectTextCuntion.value = -1;
  historyList.value = fuzzySearch(val)
  if (historyList.value.length > 0) {
    if (isBlur.value) showHistory.value = true
  } else {
    showHistory.value = false
  }
}

// 输入框聚焦事件
const focus = () => {
  selectTextCuntion.value = -1;
  isBlur.value = true
  getQueryHistory(queryText.value)
}

// 输入框失焦事件
const blur = () => {
  isBlur.value = false;
  setTimeout(() => {
    showHistory.value = false
  }, 200)
}

// 设置搜索引擎
const setSearchEngineKey = (key: AllowedSearchEnginesOptions) => {
  searchEngineKey.value = key
  isOption.value = false
}

// 移除搜索历史项
const removeHistoryItem = (item: string) => {
  removeHistory(item);
  getQueryHistory(queryText.value);
  setTimeout(() => {
    inputRef.value?.focus()
  }, 200)
}

const handleDoubleClick = () => {
  router.push({ name: 'HidePage' });
}

const selectTextCuntion = ref(-1);
onMounted(() => {
  inputRef.value?.focus();
  // 监听键盘上下键事件
  document.addEventListener('keydown', (e) => {
    if (e.key === 'ArrowUp' || e.key === 'ArrowDown') {
      e.preventDefault();
      if (e.key === 'ArrowUp') {
        if (selectTextCuntion.value > 0) {
          selectTextCuntion.value--
        } else {
          selectTextCuntion.value = historyList.value.length - 1
        }
      }
      else if (e.key === 'ArrowDown') {
        if (selectTextCuntion.value < historyList.value.length - 1) {
          selectTextCuntion.value++
        } else {
          selectTextCuntion.value = 0
        }
      }
    }
    // 监听回车键事件
    if (e.key === 'Enter') {
      e.preventDefault();
      if (selectTextCuntion.value != -1) {
        setQueryText(historyList.value[selectTextCuntion.value])
      }
    }
  })
})
</script>

<style lang="scss" scoped>
.index {
  width: 100vw;
  height: 100vh;
  background-image: url('@/assets/index/background.jpg');
  background-size: cover;
  background-position: center;
  display: flex;
  align-items: center;
  justify-content: flex-start;
  flex-direction: column;
  overflow: auto;
  padding-bottom: 10em;

  .time {
    margin-top: 3em;
    margin-bottom: 1em;
    color: rgb(255, 255, 255);
    font-size: 3em;
    cursor: pointer;
    font-weight: 550;
    user-select: none;
    -webkit-user-select: none;
    -moz-user-select: none;
  }

  &.blur-background::before {
    content: "";
    display: block;
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background-color: rgba(255, 255, 255, .1);
    backdrop-filter: blur(1em);
    z-index: 0;
  }

  &.blur-background {
    .search-box {
      background-color: rgba(255, 255, 255, .3);
      backdrop-filter: blur(0.3em);
    }
  }

  .search-box {
    border: 0.1em solid #ccc;
    border-radius: .2em;
    width: 25em;
    max-width: 90%;
    display: flex;
    align-items: center;
    z-index: 1;
    background-color: rgba(255, 255, 255, .1);
    backdrop-filter: blur(0.1em);
    padding: 0 .6em;

    &:hover {
      background-color: rgba(255, 255, 255, .3);
      backdrop-filter: blur(0.3em);
    }

    .search-icon {
      width: 1.2em;
      height: 1.2em;
      cursor: pointer;
    }


    .icon-select {
      opacity: 0;
      width: 1.2em;
      height: 1.2em;
      position: absolute;
      border: 0;
      cursor: pointer;

      option {
        font-size: 1em;
        padding: 0.3em 0.5em;
        display: flex;
        align-items: center;

        &::before {
          content: '';
          display: inline-block;
          width: 1em;
          height: 1em;
          margin-right: 0.5em;
          background-size: contain;
          background-repeat: no-repeat;
        }

        &[value="google"]::before {
          background-image: url('@/assets/index/google.svg');
        }

        &[value="baidu"]::before {
          background-image: url('@/assets/index/baidu.svg');
        }

        // 添加其他搜索引擎的图标
        // &[value="other"]::before {
        //   background-image: url('@/assets/index/other.svg');
        // }
      }
    }

    .search-input {
      width: calc(100% - 3.2em);
      height: 100%;
      position: relative;

      .search {
        width: 100%;
        height: 100%;
        padding: .5em;
        background-color: transparent;
        border: 0;
        outline: none;
        font-size: 1em;
        caret-color: rgb(50, 50, 50);
        color: rgb(50, 50, 50);
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
        vertical-align: middle;
        display: inline-block;

        &.focus {
          border: 2px solid rgb(179, 209, 255);
          border-bottom: 0;
          border-radius: 5px;
          border-bottom-left-radius: 0px;
          border-bottom-right-radius: 0px;
        }
      }

      .history-list {
        background-color: rgba(255, 255, 255, .3);
        backdrop-filter: blur(0.3em);
        padding: 0.5em;
        position: absolute;
        width: 100%;
        border: 2px solid rgb(179, 209, 255);
        border-top: 0;
        border-radius: 5px;
        border-top-left-radius: 0px;
        border-top-right-radius: 0px;

        ul>li {
          width: 100%;
          list-style: none;
          padding: 0.5em;
          cursor: pointer;
          display: flex;
          justify-content: space-between;

          div {
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
            vertical-align: middle;
            display: inline-block;
            width: calc(100% - 2rem);
          }

          &:hover {
            background-color: rgba(255, 255, 255, .5);
            backdrop-filter: blur(0.5em);
          }

          &.select {
            background-color: #fff;
          }
        }
      }
    }

    .search-button {
      user-select: none;
      -webkit-user-select: none;
      -moz-user-select: none;
    }

    button {
      background: none;
      border: none;
      color: inherit;
      padding: 0;
      margin: 0;
      font-family: inherit;
      cursor: pointer;
      font-size: 1em;
      mix-blend-mode: difference;
      text-shadow: 0.1em 0.1em 0.1em #fff;
      width: 2em;
    }
  }
}

// 媒体查询
@media (max-width: 1000px) {
  .index {
    font-size: 1.5em;
  }
}

// 媒体查询
@media (max-width: 700px) {
  .index {
    font-size: 2em;
  }
}

// 媒体查询
@media (max-width: 360px) {
  .index {
    font-size: 2.5em;
  }
}
</style>
